import {Component, Input, OnInit} from '@angular/core';
import {ModalController} from '@ionic/angular';
import {HttpService} from '../../shared/service/http.service';
import {AppGlobalService} from '../../shared/service/app-global.service';
import {MessageService} from '../../shared/service/message.service';

@Component({
    selector: 'app-search',
    templateUrl: './search.component.html',
    styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {

    @Input() pageId: string;

    @Input() name: string;

    @Input() currentCity: string;

    cityCode: number;      // 城市code

    keyword: string = '';   // 搜索关键词

    hasSearched: Boolean = false;     // 是否已经搜索

    listId: String = '';     // 列表请求参数id

    searchArr: any[];       // 搜索历史记录数组

    pageNo: Number = 1;      // 当前页数，默认1

    pageSize: Number = 2;    // size

    pageTotal: number;      // 数量

    tagData: any;        // 搜索结果数据

    hasList: Boolean = false;       // 搜索结果list是否有数据

    isHot: Boolean = true;

    sessionId: string;

    tabList: any[];

    constructor(
        private modalController: ModalController,
        private http: HttpService,
        private appGlobalService: AppGlobalService,
        private message: MessageService
    ) {
    }

    ngOnInit() {

        this.sessionId = localStorage.getItem('sessionId');

        this.cityCode = JSON.parse(localStorage.getItem('position')).code;

        this.searchArr = JSON.parse(localStorage.getItem('searchHistoryArr'))
            ? JSON.parse(localStorage.getItem('searchHistoryArr')) : [];
        /*this.searchArr = ['白石洲 餐饮', '白石洲','南油火锅店'];*/

        this.tabList = [{
            'name': '热门',
            'active': true
        }, {
            'name': '转让出租',
            'active': false
        }];

        const param = {
            'pageId': this.pageId,
            'params': {},
            'sessionId': this.sessionId
        };
        this.http.post('application/page', param, res => {
            const pageData = JSON.parse(res['script']);
            this.listId = pageData.views[0].tags[0].appListData.key;
        });
    }

    focusInput() {
        this.hasSearched = false;
        this.keyword = '';
        this.hasList = false;
    }

    search(str) {
        this.hasSearched = true;
        this.tagData = undefined;
        const len = this.searchArr.length;
        if (!str) {
            if (this.keyword !== '' && this.searchArr.indexOf(this.keyword) === -1) {
                this.searchArr.unshift(this.keyword);
                if (len >= 10) {
                    this.searchArr.pop();
                }
                localStorage.setItem('searchHistoryArr', JSON.stringify(this.searchArr));
            }
        } else {
            this.keyword = str;
        }
        this.loadData();
    }

    clearHistory() {
        this.searchArr = [];
        localStorage.removeItem('searchHistoryArr');
    }

    dismiss() {
        this.modalController.dismiss();
    }

    loadData() {
        if (this.keyword !== '') {
            const params = {
                content: {
                    keyword: {
                        'value': this.keyword,
                        'name': this.name
                    },
                    pageNo: this.pageNo,
                    pageSize: this.pageSize
                },
                id: this.listId,
                sessionId: this.sessionId
            };
            params.content[this.currentCity] = this.cityCode;
            console.log(params);
            this.message.sendMessage(params);

            // 请求获取新数据
            this.http.post('application/submit', params, res => {
                console.log(res);
                const result = JSON.parse(res['data']['data']);
                console.log(result);
                // 请求数据成功
                if (res['success'] && result.data.data) {
                    // 筛选数据
                    this.tagData = {
                        appListData: result
                    };
                    this.hasList = result.data.data && result.data.data.length > 0;
                } else {
                    // 请求数据失败
                    this.appGlobalService.showToast(res['message'], 2000, 'middle');
                }
            });
        } else {
            this.hasSearched = false;
        }
    }

    tab(num, bool) {
        this.tagData = undefined;
        this.isHot = bool;
        this.pageSize = num;
        this.loadData();
    }
}
